package cn.zyx.controller;

import cn.zyx.Config.WeixinPayProperties;
import cn.zyx.common.ReturnUtils;
import cn.zyx.common.WXPayUtil;
import cn.zyx.entity.ReturnPay;
import com.github.wxpay.sdk.WXPayConstants;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zzp
 * @since 2022/1/17 18:29
 */
@RestController
//@Service
public class ReturnPayApi {
    /*调用退款接口，取消订单*/


    /**
     *
     * @param orderNum 订单号
     * @param money  退款金额
     * @return
     */
    @RequestMapping("/refund")
    @ResponseBody
    public Map<String, Object> refund(String orderNum,String desc,String money,HttpServletResponse response){
        System.out.println(money);
        // 返回参数
        Map<String, Object> resMap = new HashMap<>();
        Date newtime = new Date();
        String resXml = "";
        try {
            // 拼接统一下单地址参数
            Map<String, Object> paraMap = new HashMap<>();
//            Order order =  orderMapper.selectByPrimaryKey(id);

//            String orderNum = order.getOrdernum();//订单号
            ;//订单号
//            String money = order.getMoney();//金额
            Integer price = Integer.valueOf(money);
//       Integer price = 1;//支付金额，单位：分，这边需要转成字符串类型，否则后面的签名会失败
            System.out.println("订单号= "+orderNum);
            // 封装必需的参数
            paraMap.put("appid", WeixinPayProperties.WX_APPID);
            paraMap.put("mch_id", WeixinPayProperties.WX_MCHID);//商家ID
            paraMap.put("nonce_str", WXPayUtil.generateNonceStr());//获取随机字符串 Nonce Str
            paraMap.put("out_trade_no", orderNum);//订单号
            paraMap.put("out_refund_no", orderNum);//商户退款单号
            paraMap.put("refund_desc", desc);//商户退款单号
            paraMap.put("total_fee",price);    //测试改为固定金额  订单金额
            paraMap.put("refund_fee",price);    //退款金额
//       paraMap.put("notify_url", WXPayConstants.notify_url);   //退款路径
            String sign = WXPayUtil.generateSignature(paraMap, WeixinPayProperties.WX_APPSECRET);//商户密码
            //生成签名. 注意，若含有sign_type字段，必须和signType参数保持一致。
            paraMap.put("sign", sign);
            //将所有参数(map)转xml格式
            String xml = WXPayUtil.mapToXml(paraMap);
            System.out.println("xml:"+xml);
            // 退款 https://api.mch.weixin.qq.com/secapi/pay/refund
            String refund_url = WXPayConstants.REFUND_URL;//申请退款路径接口
            System.out.println("refund_url:"+refund_url);
            //发送post请求"申请退款"
            String xmlStr = ReturnUtils.doRefund(refund_url, xml);
//            System.out.println("退款xmlStr:"+xmlStr);
            /*退款成功回调修改订单状态*/
            if (xmlStr.indexOf("SUCCESS") != -1) {
                Map<String, Object> map = WXPayUtil.xmlToMap(xmlStr);//XML格式字符串转换为Map
                if(map.get("return_code").equals("SUCCESS")){
                    resMap.put("success",true);//此步说明退款成功
                    resMap.put("data","退款成功");
                    System.out.println("退款成功");
                    Date refundtime = new Date();
                    Integer ordertype = -1;//-1取消订单
                    String complete = "已取消";
                    try {
//                        orderMapper.updateRefundByOrdersNum(orderNum,ordertype,refundtime,complete);
                        //告诉微信服务器收到信息了，不要在调用回调action了========这里很重要回复微信服务器信息用流发送一个xml即可
                        resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                                + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                        BufferedOutputStream out = new BufferedOutputStream(
                                response.getOutputStream());
                        out.write(resXml.getBytes());
                        out.flush();
                        out.close();
//                        System.err.println("返回给微信的值："+resXml.getBytes());
                    }catch (Exception e){
                        resMap.put("fail","订单状态修改失败");
                    }
                }
            }else {
                resMap.put("success","fail");//此步说明退款成功
                resMap.put("data","退款失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resMap;
    }
}
